package com.zealfi.wk.command;

import com.netflix.hystrix.HystrixObservableCommand;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import rx.Observable;

/**
 * Created by kuan at 2018-04-13 下午 3:41
 */
public class ObservableCommand<T> extends HystrixObservableCommand<T> {

    private RestTemplate restTemplate;
    private String url;
    private Long id;
    private Class<T> tClass;

    public ObservableCommand(Setter setter, Class<T> tClass, RestTemplate restTemplate, String url, Long id) {
        super(setter);
        this.restTemplate = restTemplate;
        this.url = url;
        this.id = id;
    }

    @Override
    protected Observable<T> construct() {
        return Observable.create((observer) -> {
            try {
                if (!observer.isUnsubscribed()) {
                    T instance = restTemplate.getForObject(url, tClass, id);
                    observer.onNext(instance);
                    observer.onCompleted();
                }
            } catch (RestClientException e) {
                observer.onError(e);
            }
        });
    }
}
